$(function () {
    var user = localStorage.getItem("user")
    if(user){
        $(".user").html(user)
        $(".login").remove()
        $(".register").remove()
        $(".logininfo").html('<a href="#" class="login-out">退出</a>')
        
    }else{
        window.location.href="./login.html"
    }
    $.ajax({
        url:"http://localhost/yidianzu/API/shopcar2.php",
        data:{user_id:user},
        dataType:"json",
        async:"false",
        success:function(data){
            console.log(data)
            var html = ""
            for(var i=0; i<data.length; i++){
                html += `
                <div class="lease-product" data-id="${data[i].Id}">
                <div class="product-layer on" id="carts_product_row_200869">
                    <div class="product-detail clearfix">
                        <div class="effective-product-info product-info width-410-px">
                            <b>
                                <input class="lease-product-cb p-cb son_check" id="p_cb_200869"
                                    type="checkbox" value="" />
                                <input class="isSale_200869" type="hidden" value="" />
                                <input class="serviceId_200869" type="hidden" value="" />
                            </b>
                            <div class="product-box clearfix">
                                <div class="pic">
                                    <a class="product-link" href="javascript:;" ><img
                                            title="${data[i].title}"
                                            src="${data[i].img_url}" style="width:100%"></a>
                                </div>
                                <div class="txt">
                                    <a class="product-link" href="javascript:;" >
                                    ${data[i].title}
                                    </a>
                                    <p class="rent-type" id="rent_type_title_200869">
                                        随租随还
                                    </p>
                                    <div class="choose-service-wrapper">
                                        <div class="choose-service-box">
                                            <i class="icon-choose-service"></i>
                                            <span class="txt-tip">选购增值服务</span>
                                            <i class="arrow icon-cart-arrow-down"></i>
                                            <i class="arrow icon-cart-arrow-up hide"></i>
                                        </div>
                                        <div class="list-layer hide"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="service-box clearfix">
                                <div class="service-add-main"></div>
                            </div>
                        </div>
                        <div class="lease-product-price">
                            <div class="month-rent-box clearfix">
                                <div class="month-rent-label">月租金：</div>
                                <div class="month-rent-list">
                                    <input id="rent_num_200869" type="hidden" value="" />
                                    <div class="month-rent-item month_rent_200869 price">
                                    ${data[i].price}(1-12月)
                                    </div>
                                    <div class="month-rent-item month_rent_200869">
                                        89.00(13-24月)
                                    </div>
                                    <div class="month-rent-item month_rent_200869">
                                        79.00(25-36月)
                                    </div>
                                </div>
                                <div class="coupon-box" id="coupon_dia_200869">
                                    <p class="coupon-title" id="coupon_title_200869">优惠券
                                        <i class="icon-coupon-arrow-down coupon-bar"></i>
                                    </p>
                                    <div class="coupon-layer hide" id="coupon_layer_200869"></div>
                                </div>
                                <div class="month-rent-box clearfix">
                                    <div class="month-rent-label">押金：</div>
                                    <div class="month-rent-list">
                                        <div class="month-rent-item deposit">1600.00</div>
                                    </div>
                                </div>

                            </div>

                        </div>
                        <div class="product-num">
                            <div class="number clearfix">
                                <a class="num-reduce disabled">-</a>
                                <a class="num">
                                    <input class="ipt-num" id="num_200869" type="text" value="1">
                                </a>
                                <a class="num-add">+</a>
                            </div>
                        </div>
                        <div class="down-pay-month" id="downPayMonth_200869">1</div>
                        <div class="lease-product-sum">
                            <p>
                                <span>首付租金：</span>
                                <i class="rentMonth_sum_200869 sum_price">${data[i].price}</i>
                            </p>
                            <p class="coupon-rent" id="rentCoupon_sum_box_200869">
                                <span>
                                    首付租金优惠：
                                </span>
                                <i id="rentCoupon_sum_200869">0.00</i>
                            </p>
                            <p>
                                <span>
                                    押金小计：
                                </span>
                                <i id="deposit_sum_200869" class="rent_price">1600.00</i>
                            </p>
                        </div>
                        <div class="product-handle">
                            <a class="delete">删除</a>
                        </div>
                    </div>
                    <div class="product-rent-info">
                        <div class="product-rent-month">
                            本商品租期为
                            <i>36</i>
                            个月，租期结束后设备归还易点租
                        </div>
                        <div class="product-rent-date">
                            <span>起租日期：</span>
                            <input class="start-rent-date" id="startRentDate_200869" type="text"
                                readonly="readonly" value="2019-12-17">
                        </div>
                    </div>
                    <div class="arrival-time-tips-box">
                        武汉仓现货，预计
                        <span class="num">3</span>
                        天内送达
                    </div>
                </div>
            </div>
                `
            }
            $(".product-content").html(html)
            // var user = localStorage.getItem("user")
            console.log($(".lease-product").data("id"))
    
    $(".logininfo").on("click",".login-out",function(){
        localStorage.removeItem("user")
        window.location.reload();
    })
    //全局的checkbox选中和未选中的样式
    var $allCheckbox = $('input[type="checkbox"]'),     //全局的全部checkbox
        $wholeChexbox = $('.whole_check'),
        $cartBox = $('.cartBox'),                       //每个分类盒子
        $shopCheckbox = $('.shopChoice'),               //每个分类的checkbox
        $sonCheckBox = $('.son_check');                 //每个分类下的商品的checkbox

    //===============================================全局全选与单个商品的关系================================
    $wholeChexbox.click(function () {
        var $checkboxs = $cartBox.find('input[type="checkbox"]');
        if ($(this).is(':checked')) {
            $checkboxs.prop("checked", true);
            
        } else {
            $checkboxs.prop("checked", false);
        }
        totalMoney();
    });


    $sonCheckBox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断：所有单个商品是否勾选
                var len = $sonCheckBox.length;
                var num = 0;
                $sonCheckBox.each(function () {
                    if ($(this).is(':checked')) {
                        // $(this).parents(".lease-product").addClass("checked")
                        num++;
                    }else{
                        // $(this).parents(".lease-product").removeClass("checked")
                    }
                });
                if (num == len) {
                    $wholeChexbox.prop("checked", true);
                }
            } else {
                //单个商品取消勾选，全局全选取消勾选
                $wholeChexbox.prop("checked", false);
            }
        })
    })

    //=======================================每个店铺checkbox与全选checkbox的关系/每个店铺与其下商品样式的变化===================================================

    //店铺有一个未选中，全局全选按钮取消对勾，若店铺全选中，则全局全选按钮打对勾。
    $shopCheckbox.each(function () {
        $(this).click(function () {
            if ($(this).is(':checked')) {
                //判断：店铺全选中，则全局全选按钮打对勾。
                var len = $shopCheckbox.length;
                var num = 0;
                $shopCheckbox.each(function () {
                    if ($(this).is(':checked')) {
                        num++;
                    }
                });
                if (num == len) {
                    $wholeChexbox.prop("checked", true);
                }

                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", true);
            } else {
                //否则，全局全选按钮取消对勾
                $wholeChexbox.prop("checked", false);
                //店铺下的checkbox选中状态
                $(this).parents('.cartBox').find('.son_check').prop("checked", false);
            }
            totalMoney();
        });
    });

    //========================================每个店铺checkbox与其下商品的checkbox的关系======================================================

    //店铺$sonChecks有一个未选中，店铺全选按钮取消选中，若全都选中，则全选打对勾
    $cartBox.each(function () {
        var $this = $(this);
        var $sonChecks = $this.find('.son_check');
        $sonChecks.each(function () {
            $(this).click(function () {
                if ($(this).is(':checked')) {
                    //判断：如果所有的$sonChecks都选中则店铺全选打对勾！
                    var len = $sonChecks.length;
                    var num = 0;
                    $sonChecks.each(function () {
                        if ($(this).is(':checked')) {
                            num++;
                        }
                    });
                    if (num == len) {
                        $(this).parents('.cartBox').find('.shopChoice').prop("checked", true);
                    }

                } else {
                    //否则，店铺全选取消
                    $(this).parents('.cartBox').find('.shopChoice').prop("checked", false);
                }
                totalMoney();
            });
        });
    });
    //=================================================商品数量==============================================
    var $plus = $('.num-add'),  //增加按钮
        $reduce = $('.num-reduce'), //减少按钮
        $all_sum = $('.ipt-num');   //数量
    if ($(".ipt-num").val() == 1) {
        $(".num-reduce").addClass('reSty');
    }
    $plus.click(function () {   //增加按钮
        var $inputVal = $(this).parents('.number').find('.ipt-num'),
            $count = parseInt($inputVal.val()) + 1,
            $obj = $(this).parents('.number').find('.num-reduce'),
            $priceTotalObj = $(this).parents('.product-detail').find('.sum_price'), //单个商品总价
            $depositObj = $(this).parents('.product-detail').find('.rent_price');
            $price = $(this).parents('.product-detail').find('.price').html(),  //单价
            $deposit = $(this).parents('.product-detail').find('.deposit').html(), //租金
            $priceTotal = $count * parseInt($price),
            $depositTotal = $count * parseInt($deposit),
           
        $inputVal.val($count);
        $priceTotalObj.html($priceTotal + ".00");
        $depositObj.html($depositTotal + ".00")
        console.log($depositObj,$depositTotal)
        // console.log($count, $price, $priceTotal, $priceTotalObj)
        if ($inputVal.val() > 1 && $obj.hasClass('reSty')) {
            $obj.removeClass('reSty');
        }
        totalMoney();
    });

    $reduce.click(function () {     //减少按钮
        var $inputVal = $(this).parents('.number').find('.ipt-num'),
            $count = parseInt($inputVal.val()) - 1,
            $priceTotalObj = $(this).parents('.product-detail').find('.sum_price'),
            $price = $(this).parents('.product-detail').find('.price').html(),  //单价
            $depositObj = $(this).parents('.product-detail').find('.rent_price');
            $priceTotal = $count * parseInt($price);
            $deposit = $(this).parents('.product-detail').find('.deposit').html(), //租金
            $depositTotal = $count * parseInt($deposit);
        if ($inputVal.val() > 1) {
            $inputVal.val($count);
            $priceTotalObj.html($priceTotal + ".00");
            $depositObj.html($depositTotal + ".00")
        }
        if ($inputVal.val() == 1 && !$(this).hasClass('reSty')) {
            $(this).addClass('reSty');
        }
        totalMoney();
    });

    $all_sum.keyup(function () {    //输入数字
        var $count = 0,
            $inputVal = $(this).parents('.number').find('.ipt-num'),
            $obj = $(this).parents('.number').find('.num-reduce'),
            $priceTotalObj = $(this).parents('.product-detail').find('.sum_price'),
            $depositObj = $(this).parents('.product-detail').find('.rent_price');
            $price = $(this).parents('.product-detail').find('.price').html(),  //单价
            $deposit = $(this).parents('.product-detail').find('.deposit').html(), //租金
            $priceTotal = 0;
            $depositTotal = 0;
        if ($(this).val() == '') {
            $(this).val('1');
        }
        $(this).val($(this).val().replace(/\D|^0/g, ''));
        $count = $(this).val();
        $priceTotal = $count * parseInt($price);
        $depositTotal = $count * parseInt($deposit);
        $(this).attr('value', $count);
        $priceTotalObj.html($priceTotal + ".00");
        $depositObj.html($depositTotal + ".00")
        totalMoney();
        if ($inputVal.val() > 1 && $obj.hasClass('reSty')) {
            $obj.removeClass('reSty');
        }
    })

    //======================================总计==========================================

    function totalMoney() {
        var total_money = 0;
        var total_count = 0;
        var total_rentmoney = 0
        var total_pricemoney = 0
        $sonCheckBox.each(function () {
            if ($(this).is(':checked')) {
                var $price = parseInt($(this).parents('.product-detail').find('.sum_price').html())
                var $rentprice = parseInt($(this).parents('.product-detail').find('.rent_price').html())
                var goods = $price + $rentprice;
                
                var num =  parseInt($(this).parents('.product-detail').find('.ipt-num').val());
                total_money += goods;
                total_count += num;
                total_rentmoney += $rentprice
                total_pricemoney += $price
            }
        });
        $(".prices").html(total_rentmoney + ".00")
        $(".rentprices").html(total_pricemoney + ".00")
        $('.pay-total').html(total_money);
        $('.bill-tit i').html(total_count);

    }

    //======================================移除商品========================================

    var $order_lists = null;
    var $order_content = '';
    
    
    $('.delete').click(function () {
        $order_lists = $(this).parents('.lease-product');
        $order_content = $order_lists.parents('.product-content');
        $car_id = $(this).parents('.lease-product').data("id")
        
        $('.shop-del').fadeIn(300);
    });

    //关闭模态框
    $('.close').click(function () {
        closeM();
    });
    $('.cancel-btn').click(function () {
        closeM();
    });
    function closeM() {
        $('.yzerro').fadeOut(300);
    }
    //确定按钮，移除商品
    
    $('.ok-btn').click(function () {
        
        $order_lists.remove();
        if($order_content.html().trim() == null || $order_content.html().trim().length == 0){
            $order_content.parents('.cartBox').remove();
            
            
        }
        $.ajax({
            url:"http://localhost/yidianzu/API/shopcar_del.php",
            data:{id:$car_id},
            async:"false",
            success:function(data){
                console.log(data)
            }
        })
        closeM();
        $sonCheckBox = $('.son_check');
        totalMoney();
        ifnull()
    })
    //清空购物车
    $(".allclear").click(function(){
        $('.allshop-clear').fadeIn(300);
        
    })
    $('.ok-btn2').click(function(){
        $(".cartBox").remove()
        closeM()
        ifnull()
    })

    //购物车为空时
    function ifnull(){
        if($(".cartBox").length == 0){
            var html = `
                    <div class="no-goods">
                        <p>
                            购物车空空的哦，您再逛逛~ 
                            <a href="./index.html">去选购 ><img src="https://resources.edianzu.com/mall_new/20191212_1/images/shootIco.gif" alt=""></a>
                        </p>
                    </div>
                `
                $(".product-list").html(html)
        }
    }
    
        }
    })
    
    

})